package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.Question;
import cn.wolfcode.trip.base.domain.User;
import cn.wolfcode.trip.base.mapper.QuestionMapper;
import cn.wolfcode.trip.base.query.QuestionQueryObject;
import cn.wolfcode.trip.base.service.IQuestionService;
import cn.wolfcode.trip.base.util.UserContext;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class QuestionServiceImpl implements IQuestionService {

    @Autowired
    private QuestionMapper questionMapper;


    @Override
    public void save(Question question) {
        //获取当前用户
        User user= UserContext.getCurrentUser();
        question.setUser(user);
        //设置当前时间
        question.setReleaseTime(new Date());
        questionMapper.insert(question);
    }

    /**
     * 提问列表
     * @param qo
     * @return
     */
    @Override
    public PageInfo query(QuestionQueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize(),qo.getOrderBy());
        List<Question> list=questionMapper.selectForList(qo);
        return new PageInfo(list);
    }

    @Override
    public Question get(Long id) {
        return questionMapper.selectByPrimaryKey(id);
    }

    @Override
    public void updatePageViews(Question question) {
        questionMapper.updatePageViews(question);
    }

    /**
     * 获取用户是否点了赞
     * @param userId 用户id
     * @param questionId 问题id
     * @return
     */
    @Override
    public int getLikeRelation(Long userId, Long questionId) {
        return questionMapper.selectLikeRelation(userId,questionId);
    }

    /**
     * 保存点赞关系
     * @param userId
     * @param questionId
     */
    @Override
    public void saveLikeRelation(Long userId, Long questionId) {
        questionMapper.saveLikeRelation(userId,questionId);
        int likeNum = questionMapper.getLikeNum(questionId);
        questionMapper.updateLikeNum(questionId,likeNum+1);
    }

    /**
     * 删除点赞关系
     * @param userId
     * @param questionId
     */
    @Override
    public void deleteLikeRelation(Long userId, Long questionId) {
        questionMapper.deleteLikeRelation(userId,questionId);
        int likeNum = questionMapper.getLikeNum(questionId);
        if (likeNum==0){
            return;
        }
        questionMapper.updateLikeNum(questionId,likeNum-1);
    }

    /**
     * 查询点赞数量
     * @return
     */
    @Override
    public int getLikeNum(Long id) {
        return questionMapper.getLikeNum(id);
    }
}
